package com.benben.springSecurity.controller;

import com.alibaba.fastjson.JSONArray;
import com.benben.springSecurity.service.impl.RedissonServiceImpl;
import com.benben.springSecurity.util.RedisUtils;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.collections4.IterableMap;
import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Controller
//@RequestMapping("test")
public class RedissonTest {

    private static final Logger log = LoggerFactory.getLogger(RedissonTest.class);


    @Autowired
    private RedissonServiceImpl redissonService;

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("/redis")
    @ResponseBody
    @Cacheable(cacheNames="user", key="'name_'+#name")
    public String test(String name) {

        System.out.println("name:"+ name);
        return name;
    }

    @RequestMapping("/getCacheByName")
    public ModelAndView getCacheByName(String name, HttpServletRequest request){
        request.setAttribute("key","name");
        request.setAttribute("value","benben2018");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("forward:addRedis");
        return mv;
    }

    @RequestMapping("/addRedis")
    @ResponseBody
    public String addRedis(String key,String value){
        redisUtils.set(key,value);
        return "add key: "+ key +",value：" +value +",success";
    }

    @RequestMapping("/addRedisList")
    @ResponseBody
    public String addRedisList(String key,String value){
        List<String> list = Arrays.asList(value.split(","));
        if(list.size()==1){
            redisUtils.set(key,value);
        }else{
            redisUtils.lSet(key,list);
        }
        return "add key: "+ key +",value：" +value +",success";
    }

    @RequestMapping("/getRedisByKey")
    @ResponseBody
    public String getRedisByKey(String key){
        List list = redisUtils.lGet(key,0,-1);
        JSONArray jsonArray = new JSONArray(list);
        return jsonArray.toJSONString();
    }

}
